package com.gitee.melin.bee.core.jdbc.dialect.impl;

import com.gitee.melin.bee.core.jdbc.dialect.AbstractJdbcDialect;
import com.gitee.melin.bee.core.jdbc.enums.DataSourceType;
import com.gitee.melin.bee.core.jdbc.relational.BeeTableType;
import com.gitee.melin.bee.core.jdbc.relational.ConnectionInfo;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import org.apache.commons.lang3.StringUtils;

public class SapHanaJdbcDialect extends AbstractJdbcDialect {

    @Override
    public DataSourceType getDataSourceType() {
        return DataSourceType.HANA;
    }

    public SapHanaJdbcDialect(ConnectionInfo connectionInfo) {
        super(connectionInfo);
    }

    public SapHanaJdbcDialect(Connection connection) {
        super(connection);
    }

    @Override
    protected Driver getDriver() throws SQLException {
        return loadDriver(DataSourceType.HANA.getDriverClass());
    }

    @Override
    protected String testConnectionSql() {
        return "select  1 as constant_number from DUMMY;";
    }

    @Override
    protected boolean filterSchema(String schemaName) {
        if (schemaName.startsWith("_SYS")
                || schemaName.equalsIgnoreCase("SYS")
                || schemaName.equalsIgnoreCase("SYSTEM")
                || schemaName.equalsIgnoreCase("BROKER_PO_USER")
                || schemaName.equalsIgnoreCase("BROKER_USER")
                || schemaName.equalsIgnoreCase("PAL_STEM_TFIDF")
                || schemaName.equalsIgnoreCase("SAP_PA_APL")
                || schemaName.equalsIgnoreCase("_SAP_METRICS_EXPORTER")
                || schemaName.equalsIgnoreCase("PAL_CONTENT")) {
            return false;
        }
        return true;
    }

    @Override
    protected String getSelectTablesSql(String tableName) {
        String sql = "SELECT TA.SCHEMA_NAME,\n"
                + "       TA.TABLE_NAME,\n"
                + "       TA.COMMENTS TABLE_COMMENT,\n"
                + "       TA.CREATE_TIME,\n"
                + "       MT.RECORD_COUNT TABLE_ROWS,\n"
                + "       MT.TABLE_SIZE DATA_SIZE,\n"
                + "       null as TABLE_TYPE,\n"
                + "       null AS TABLE_ENGINE,\n"
                + "       null TABLE_PARTITION,\n"
                + "       null UPDATE_TIME\n"
                + "FROM SYS.TABLES AS TA\n"
                + "       LEFT JOIN SYS.M_TABLES AS MT ON TA.SCHEMA_NAME = MT.SCHEMA_NAME AND TA.TABLE_NAME = MT.TABLE_NAME\n"
                + "WHERE TA.SCHEMA_NAME = ?";
        if (StringUtils.isNotBlank(tableName)) {
            sql += " AND TABLE_NAME = :tableName";
        }
        return sql;
    }

    @Override
    protected String getDDLColumnName(BeeTableType type) {
        throw new IllegalArgumentException("未定义 DDLColumnName");
    }
}
